package happy.town.case_JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class TestTrascation {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstm1 = null;
        PreparedStatement pstm2 = null;
        try {
            //加载驱动获取连接
            conn = JdbcUtils02.getconnection();
            //设置jdbc事务手动提交
            conn.setAutoCommit(false);
            //事务1：降职,事务2：降薪
            //分析：若白展堂从经理变成了小职员，他的奖金也要减少
            String sql1 = "update emp set job='clerk' where ename='白展堂'";
            pstm1 = conn.prepareStatement(sql1);
            pstm1.executeUpdate();
            //comm=4000不符合comm的数据类型，不大于3位数，所以异常回滚
            //String sql2="update emp set comm=4000 where ename='白展堂'";
            String sql2 = "update emp set comm=100 where ename='白展堂'";
            pstm2 = conn.prepareStatement(sql2);
            pstm2.executeUpdate();
            //提交事务：如果事务1和2都成功执行了就提交事务
            //否则捕捉异常，在catch里面执行事务回滚
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                JdbcUtils02.release(null, pstm2, conn);
                JdbcUtils02.release(null, pstm1, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
